﻿using Furion.DependencyInjection;
using Furion.FriendlyException;

namespace EMC.VISITOR.Core;
/// <summary>
/// 意见反馈服务
/// </summary>
[ApiDescriptionSettings(Order = 270)]
public partial class SysFeedbackService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<SysFeedback> _rep;
    public SysFeedbackService(SqlSugarRepository<SysFeedback> rep)
    {
        _rep = rep;
    }
    #region 代码生成
    /// <summary>
    /// 分页查询意见反馈
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public virtual async Task<SqlSugarPagedList<SysFeedbackOutput>> Page(SysFeedbackInput input)
    {
        var context = _rep.AsQueryable().FilterDelete();
        var query = context.WhereIF(input.Type.HasValue, u => u.Type == input.Type)
            .Select<SysFeedbackOutput>();
        query = query.OrderByDescending(r => r.CreateTime);
        return query.ToPagedList(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加意见反馈
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<JRResult<string>> Add(AddSysFeedbackInput input)
    {
        var entity = input.Adapt<SysFeedback>();
        var doSomeResult = await entity.DoSomeThing(_rep.Context);
        if (!doSomeResult.Item1)
            return CustomeResult.Fail<string>(doSomeResult.Item2);
        bool isNeedReplicatings = false;
        string repString = null;
        Expression<Func<SysFeedback, bool>> whereExpression = r => true;
        if (isNeedReplicatings)
        {
            isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);
            if (!isNeedReplicatings)
            {
                await _rep.InsertAsync(entity);
            }
            else
            {
                //系统中存在已删除数据，还原数据
                whereExpression = whereExpression.And(r => r.IsDelete == true);
                var exsitModel = await _rep.GetFirstAsync(whereExpression);
                if (exsitModel != null)
                {
                    entity.Id = exsitModel.Id; //还原已删除的数据
                    entity.IsDelete = false;
                    await _rep.UpdateAsync(entity);
                    isNeedReplicatings = false;
                }
            }
        }
        else
        {
            await _rep.InsertAsync(entity);
        }
        return new JRResult<string>
        {
            Code = !isNeedReplicatings ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest,
            Message = !isNeedReplicatings ? "新增成功！" : $"系统中存在重复的【{repString}】，不能重复添加！",
            Result = null,
            Type = !isNeedReplicatings ? "success" : "error",
            Extras = UnifyContext.Take(),
            Time = DateTime.Now
        };
    }

    /// <summary>
    /// 删除意见反馈
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public virtual async Task Delete(DeleteSysFeedbackInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _rep.FakeDeleteAsync(entity);   //假删除
    }

    /// <summary>
    /// 更新意见反馈
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task<JRResult<string>> Update(UpdateSysFeedbackInput input)
    {
        var entity = input.Adapt<SysFeedback>();
        var doSomeResult = await entity.DoSomeThing(_rep.Context);
        if (!doSomeResult.Item1)
            return CustomeResult.Fail<string>(doSomeResult.Item2);
        bool isNeedReplicatings = false;
        string repString = null;
        Expression<Func<SysFeedback, bool>> whereExpression = r => r.Id != entity.Id;
        if (isNeedReplicatings)
        {
            isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);
            if (!isNeedReplicatings)
            {
                await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await entity.DoSomeThingSaveChildren(_rep.Context);
            }
        }
        else
        {
            await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            await entity.DoSomeThingSaveChildren(_rep.Context);
        }

        return new JRResult<string>
        {
            Code = !isNeedReplicatings ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest,
            Message = !isNeedReplicatings ? "更新成功！" : $"系统中存在重复的【{repString}】，不能修改！",
            Result = null,
            Type = !isNeedReplicatings ? "success" : "error",
            Extras = UnifyContext.Take(),
            Time = DateTime.Now
        };
    }

    /// <summary>
    /// 保存意见反馈
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Save")]
    public async Task<JRResult<string>> Save(UpdateSysFeedbackInput input)
    {
        var entity = input.Adapt<SysFeedback>();
        await entity.SaveDoSomeThing(_rep.Context);
        bool isNeedReplicatings = false;
        string repString = null;
        Expression<Func<SysFeedback, bool>> whereExpression = r => r.Id != entity.Id;
        if (isNeedReplicatings)
        {
            isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);
            if (!isNeedReplicatings)
            {
                await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await entity.DoSomeThingSaveChildren(_rep.Context);
            }
        }
        else
        {
            await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            await entity.DoSomeThingSaveChildren(_rep.Context);
        }

        return new JRResult<string>
        {
            Code = !isNeedReplicatings ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest,
            Message = !isNeedReplicatings ? "更新成功！" : $"系统中存在重复的【{repString}】，不能修改！",
            Result = null,
            Type = !isNeedReplicatings ? "success" : "error",
            Extras = UnifyContext.Take(),
            Time = DateTime.Now
        };
    }

    /// <summary>
    /// 保存意见反馈包含关联表
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "SaveWithChildren")]
    public async Task<JRResult<string>> SaveWithChildren(SysFeedback entity)
    {
        await entity.SaveDoSomeThing(_rep.Context);
        bool isNeedReplicatings = false;
        string repString = null;
        Expression<Func<SysFeedback, bool>> whereExpression = r => r.Id != entity.Id;
        if (isNeedReplicatings)
        {
            isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);
            if (!isNeedReplicatings)
            {
                await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await entity.DoSomeThingSaveChildren(_rep.Context);
            }
        }
        else
        {
            await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
            await entity.DoSomeThingSaveChildren(_rep.Context);
        }

        return new JRResult<string>
        {
            Code = !isNeedReplicatings ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest,
            Message = !isNeedReplicatings ? "更新成功！" : $"系统中存在重复的【{repString}】，不能修改！",
            Result = null,
            Type = !isNeedReplicatings ? "success" : "error",
            Extras = UnifyContext.Take(),
            Time = DateTime.Now
        };
    }

    /// <summary>
    /// 获取意见反馈
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<SysFeedback> Get([FromQuery] QueryByIdSysFeedbackInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取意见反馈详情
    /// </summary>
    [HttpGet]
    public async Task<dynamic> Info(string tableName, long id)
    {
        var logConfigId = SqlSugarConst.GetDataBaseConfigId(tableName);
        var _db = _rep.AsTenant().GetConnectionScope(logConfigId);
        var dt = await _db.SqlQueryable<dynamic>($"select * from {tableName} where Id={id}").ToListAsync();
        dynamic clay = Clay.Object(dt.FirstOrDefault());
        return TypeHelper.SetDynamicZh(tableName, clay);
    }

    /// <summary>
    /// 获取意见反馈列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<SysFeedbackOutput>> List([FromQuery] SysFeedbackInput input)
    {
        return await _rep.AsQueryable().Select<SysFeedbackOutput>().ToListAsync();
    }





    /// <summary>
    /// 导出意见反馈
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Export"), NonUnify]
    public async Task<IActionResult> Export(SysFeedbackInput input)
    {
        var query = _rep.AsQueryable().FilterDelete()
            .WhereIF(input.Type.HasValue, u => u.Type == input.Type)
            .Select<ExportImportSysFeedbackDto>();
        query = query.OrderByDescending(r => r.CreateTime);
        var list = await query.ToListAsync();
        IExcelExporter excelExporter = new ExcelExporter();
        var res = await excelExporter.ExportAsByteArray(list);
        return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "意见反馈.xlsx" };
    }

    /// <summary>
    /// 导入
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<JRResult<string>> Import(IFormFile file)
    {
        IImporter Importer = new ExcelImporter();
        var importData = await Importer.Import<ExportImportSysFeedbackDto>(file.OpenReadStream());
        if (importData.HasError == true) { return CustomeResult.Fail<string>("导入错误"); }
        if (importData.Exception != null) { return CustomeResult.Fail<string>(importData.Exception.ToString()); }
        if (importData.RowErrors.Count > 0) { return CustomeResult.Fail<string>(JSON.Serialize(importData.RowErrors)); }
        if (importData.Data == null) { return CustomeResult.Fail<string>("导入的数据量不能为空！"); }
        if (importData.Data.Count <= 0) { return CustomeResult.Fail<string>("导入的数据量为0个！"); }

        var models = importData.Data.Adapt<List<SysFeedback>>();
        bool isNeedReplicatings = false;
        string repString = null;
        Expression<Func<SysFeedback, bool>> whereExpression = r => true;
        if (isNeedReplicatings)
        {
            isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);

            if (!isNeedReplicatings)
            {
                await _rep.AsInsertable(models).ExecuteCommandAsync();
            }
            else
                return CustomeResult.Fail<string>(repString);
        }
        else
        {
            await _rep.AsInsertable(models).ExecuteCommandAsync();
        }

        return CustomeResult.Success<string>("导入成功!");
    }


    /// <summary>
    /// 模板下载
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet]
    public async Task<IActionResult> TemplateDown()
    {
        IImporter Importer = new ExcelImporter();
        var template = await Importer.GenerateTemplateBytes<ExportImportSysFeedbackDto>();
        return new FileStreamResult(new MemoryStream(template), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "意见反馈导入模板.xlsx" };
    }
    #endregion
}

